Interacting with the Incoming HTTP Request

As you saw earlier in this chapter, the basic flow of a web application begins with a client requesting a web page, possibly filling in user information, and clicking a “Submit button” to post back the HTML form data to a given web page for processing. In most cases, the opening tag of the form statement specifies an action attribute and a method attribute that indicates the file on the web server that will be sent the data in the various HTML widgets, as well as the method of sending this data (GET or POST):

<form name="defaultPage" id="defaultPage"
    action="http://localhost/Cars/ClassicAspPage.asp" method = "GET">
...
</form>

All ASP.NET pages support the System.Web.UI.Page.Request property, which provides access to an instance of the HttpRequest class type (see Table 32-5 for some common members of this class).

Table 32-5. Members of the HttpRequest Type

Member Meaning in Life
ApplicationPath Gets the ASP.NET application’s virtual application root path on the server
Browser Provides information about the capabilities of the client browser
Cookies Gets a collection of cookies sent by the client browser
FilePath Indicates the virtual path of the current request
Form Gets a collection of HTTP form variables
Headers Gets a collection of HTTP headers
HttpMethod Indicates the HTTP data transfer method used by the client (GET, POST)
IsSecureConnection Indicates whether the HTTP connection is secure (i.e., HTTPS)
QueryString Gets the collection of HTTP query string variables
RawUrl Gets the current request’s raw URL
RequestType Indicates the HTTP data transfer method used by the client (GET, POST)
ServerVariables Gets a collection of web server variables
UserHostAddress Gets the IP host address of the remote client
UserHostName Gets the DNS name of the remote clien

In addition to these properties, the HttpRequest type has a number of useful methods, including the following:

Obtaining Brower Statistics

The first interesting aspect of the HttpRequest type is the Browser property, which provides access to an underlying HttpBrowserCapabilities object. HttpBrowserCapabilities, in turn, exposes numerous members that allow you to programmatically investigate statistics regarding the browser that sent the incoming HTTP request.

Create a new ASP.NET website named FunWithPageMembers (again, elect to use the File System option). Your first task is to build a UI that allows users to click a Button web control (named btnGetBrowserStats) to view various statistics about the calling browser. These statistics will be generated dynamically and attached to a Label type (named lblOutput). The button’s Click event handler is as follows:

protected void btnGetBrowserStats_Click(object sender, EventArgs e)
{
    string theInfo = "";
    theInfo += string.Format("<li>Is the client AOL? {0}</li>",
        Request.Browser.AOL);
    theInfo += string.Format("<li>Does the client support ActiveX? {0}</li>",
        Request.Browser.ActiveXControls);
    theInfo += string.Format("<li>Is the client a Beta? {0}</li>",
        Request.Browser.Beta);
    theInfo += string.Format("<li>Does the client support Java Applets? {0}</li>",
        Request.Browser.JavaApplets);
    theInfo += string.Format("<li>Does the client support Cookies? {0}</li>",
        Request.Browser.Cookies);
    theInfo += string.Format("<li>Does the client support VBScript? {0}</li>",
        Request.Browser.VBScript);
    lblOutput.Text = theInfo;
}

Here you are testing for a number of browser capabilities. As you would guess, it is (very) helpful to discover a browser’s support for ActiveX controls, Java applets, and client-side VBScript code. If the calling browser does not support a given web technology, your *.aspx page will be able to take an alternative course of action.

Access to Incoming Form Data

Other aspects of the HttpResponse type are the Form and QueryString properties. These two properties allow you to examine the incoming form data using name/value pairs. While you could make use of the HttpRequest.Form and HttpRequest.QueryString properties to access client-supplied form data on the web server, ASP.NET provides a more elegant, object-oriented approach. Given that ASP.NET supplies you with server-side web controls, you are able to treat HTML UI elements as true objects. Therefore, rather than obtaining the value within a text box as follows

protected void btnGetFormData_Click(object sender, System.EventArgs e)
{
    // Get value for a widget with ID txtFirstName.
    string firstName = Request.Form("txtFirstName");
    // Use this value in your page...
}

you can simply ask the server-side widget directly via the Text property for use in your program, like so

protected void btnGetFormData_Click(object sender, System.EventArgs e)
{
    // Get value for a widget with ID txtFirstName.
    string firstName = txtFirstName.Text;
    
    // Use this value in your page...
}

Not only does this approach lend itself to solid OO principles, but also you do not need to concern yourself with how the form data was submitted (GET or POST) before obtaining the values. Furthermore, working with the widget directly is much more type-safe, given that typing errors are discovered at compile time rather than runtime. Of course, this is not to say that you will never need to make use of the Form or QueryString property in ASP.NET; rather, the need to do so has greatly diminished and is usually optional.

The IsPostBack Property

Another very important member of HttpRequest is the IsPostBack property. Recall that “postback” refers to a web page posting back to the same URL at the Web server. Given this definition, understand that the IsPostBack property will return true if the current HTTP request has been sent by a user currently in session, and false if this is the user’s first interaction with the page.

Typically, the need to determine whether the current HTTP request is indeed a postback is most helpful when you wish to execute a block of code only the first time the user accesses a given page. For example, you may wish to populate an ADO.NET DataSet when the user first accesses an *.aspx file and cache the object for later use. When the caller returns to the page, you can avoid the need to hit the database unnecessarily (of course, some pages may require that the DataSet always be updated upon each request, but that is another issue). Assuming your *.aspx file has handled the page’s Load event (described in detail later in this chapter), you could programmatically test for postback conditions as follows:

protected void Page_Load(object sender, System.EventArgs e)
{
    // Fill DataSet only the very first time
    // the user comes to this page.
    if (!IsPostBack)
    {
        // Populate DataSet and cache it!
    }
    // Use cached DataSet.
}